package com.dify.tool.service.impl;

import cn.hutool.core.bean.BeanUtil;
import co.elastic.clients.elasticsearch._types.SortOrder;
import com.dify.tool.api.dto.AgentHistoryRecordAddDTO;
import com.dify.tool.api.vo.AgentHistoryRecordVO;
import com.dify.tool.common.utils.ElasticsearchUtil;
import com.dify.tool.service.IAgentHistoryRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 代码生成业务表 服务实现类
 * </p>
 *
 * @author shl
 * @since 2025-07-28
 */
@Slf4j
@Service
public class AgentHistoryRecordServiceImpl implements IAgentHistoryRecordService {

    @Value("${spring.elasticsearch.index.agentHistoryRecord}")
    private String index;

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    @Override
    public void add(AgentHistoryRecordAddDTO dto) {
        // TODO 预留用户关联逻辑

        elasticsearchUtil.createDocument(index, dto);
    }

    @Override
    public List<AgentHistoryRecordVO> queryBySessionId(String sessionId) {
        // TODO 预留用户关联逻辑

        ElasticsearchUtil.SearchResult<AgentHistoryRecordAddDTO> result = elasticsearchUtil.search(
                index,
                AgentHistoryRecordAddDTO.class,
                s -> s.query(q -> q
                                .match(p -> p.field("sessionId").query(sessionId)))
                        .sort(so -> so.field(f -> f.field("sendTime").order(SortOrder.Desc)))
        );
        return BeanUtil.copyToList(result.results(), AgentHistoryRecordVO.class);
    }

    @Override
    public void likeOrDislike(Long messageId, Integer isLike) {
        // TODO 预留用户关联逻辑

        elasticsearchUtil.updateByField(index, "messageId", messageId, "isLike", isLike);
    }

    @Override
    public List<AgentHistoryRecordVO> sessionList() {
        // TODO 预留用户关联逻辑

        ElasticsearchUtil.SearchResult<AgentHistoryRecordVO> result = elasticsearchUtil.search(
                index,
                AgentHistoryRecordVO.class,
                s -> s.query(q -> q
                        .matchAll(p -> p))
        );
        List<AgentHistoryRecordVO> agentHistoryRecordVOList = result.results();

        Map<String, AgentHistoryRecordVO> map = agentHistoryRecordVOList.stream()
                .collect(Collectors.groupingBy(
                        // 分组键：sessionId
                        AgentHistoryRecordVO::getSessionId,
                        // 对每个分组的处理：筛选+取最小sendTime
                        Collectors.collectingAndThen(
                                // 步骤1：筛选出messageType=1的记录
                                Collectors.filtering(
                                        vo -> vo.getMessageType() == 1,  // 过滤条件
                                        // 步骤2：在筛选后的集合中，取sendTime最小的记录
                                        Collectors.minBy(Comparator.comparing(AgentHistoryRecordVO::getSendTime))
                                ),
                                // 处理结果：将Optional转换为具体对象（无符合条件的记录则为null）
                                optional -> optional.orElse(null)
                        )
                ))
                // 过滤掉值为null的条目（即该sessionId下无messageType=1的记录）
                .entrySet().stream()
                .filter(entry -> entry.getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        return map.values().stream().sorted(Comparator.comparing(AgentHistoryRecordVO::getSendTime).reversed()).collect(Collectors.toList());
    }
}
